import {
    createRouter,
    createWebHistory,
    RouterOptions,
    Router
} from 'vue-router'

import { routes } from './routes'
import { RouteRecordRaw } from 'vue-router/dist/vue-router.js';


function getRouterList( routes: Array<RouteRecordRaw>=[] ) :Array<RouteRecordRaw>  {

    let homeRouterItem = getHomeRouteItem(routes);
    let loginRouterItem  = getLoginRouteItem(routes);
    let homeChildren = getHomeRouterList(homeRouterItem.children || []);
    return [
        loginRouterItem,
        {
            ...homeRouterItem,
            children: homeChildren
        }
    ];
}

function getHomeRouterList( dataList: Array<RouteRecordRaw>=[] ):Array<RouteRecordRaw> {
    
    let routes: Array<RouteRecordRaw> = [];
    for( let i=0; i<dataList.length; i++ ){
        let item = dataList[i];
        if( item.component ){
            routes.push(item);
        }
        if( Array.isArray( item.children ) && item.children.length ){
           let subList = getHomeRouterList(item.children);
           routes.push(...subList);
        }
    }
    return routes;
}


const getHomeRouteItem = ( dataList:Array<RouteRecordRaw> =[] )=>{
    return dataList.find(item=>{
        return item.name == "Home";
    })
}
const getLoginRouteItem =  ( dataList:Array<RouteRecordRaw> =[] )=>{
    return dataList.find(item=>{
        return item.name == "Login";
    })
}

const aa = getRouterList(routes);
console.log("aa", aa)

const history: Router = createWebHistory();
const options: RouterOptions = {
    history,
    routes: getRouterList(routes),
    scrollBehavior( to, from, savedPosition ){
        if( savedPosition ){
            return savedPosition;
        }
        return {
            top: 0
        }
    }
}
const router = createRouter(options);

export default router;